package com.scau.wrongtitle.service;

import com.scau.wrongtitle.bean.RawWrongTitle;
import com.scau.wrongtitle.bean.RawWrongTitleBody;
import com.scau.wrongtitle.bean.WrongTitleBean;
import com.scau.wrongtitle.domin.*;
import com.scau.wrongtitle.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class WrongTitleService {
    private final WrongTitleRepository wrongTitleRepository;
    private final TagTitleRecordRepository tagTitleRecordRepository;
    private final QuestionOptionRepository questionOptionRepository;
    private final QuestionAnswerRepository questionAnswerRepository;
    private final TitleRecordRepository titleRecordRepository;
    private final RestTemplateService restTemplateService;
    private final UserInfoService userInfoService;

    @Value("${subjects}")
    String subjects;
    @Value("${questionType}")
    String questionType;

    @Autowired
    public WrongTitleService(WrongTitleRepository wrongTitleRepository,
                             TagTitleRecordRepository tagTitleRecordRepository,
                             TitleRecordRepository titleRecordRepository,
                             QuestionOptionRepository questionOptionRepository,
                             QuestionAnswerRepository questionAnswerRepository,
                             UserInfoService userInfoService) {
        this.wrongTitleRepository = wrongTitleRepository;
        this.tagTitleRecordRepository = tagTitleRecordRepository;
        this.titleRecordRepository = titleRecordRepository;
        this.questionOptionRepository = questionOptionRepository;
        this.questionAnswerRepository = questionAnswerRepository;
        this.userInfoService = userInfoService;
        restTemplateService = new RestTemplateService();
    }

    public List<WrongTitleBean> getUserTitle(long uid, String grade, String subject){
        List<WrongTitle> wrongTitleList = wrongTitleRepository.getUserTitle(uid, grade, subject);
        List<WrongTitleBean> titleBeans = new ArrayList<>();
        for (WrongTitle title : wrongTitleList) {
            WrongTitleBean titleBean = loadWrongTitleToBean(uid, title);
            titleBeans.add(titleBean);
        }
        return titleBeans;
    }

    public WrongTitleBean test(long uid, long qid){
        WrongTitle title = wrongTitleRepository.findByQuestionId(qid);
        return loadWrongTitleToBean(uid, title);
    }

    private WrongTitleBean loadWrongTitleToBean(long uid, WrongTitle title){
        long questionId = title.getQuestionId();
        TitleRecord record = titleRecordRepository.findByUserIdAndQuestionId(uid, questionId);
        List<String> questionOption = questionOptionRepository.findAllByQuestionId(questionId);
        List<String> questionAnswer = questionAnswerRepository.findAllByQuestionId(questionId);
        List<String> questionTag = tagTitleRecordRepository.findByQuestionId(questionId);
        List<String> questionOriginal = new ArrayList<String>(){{
            addAll(Arrays.asList(record.getQuestionOriginal().split(" ")));
        }};
        return  new WrongTitleBean(title,questionOption,questionAnswer,questionTag, questionOriginal,
                record.isFavorite(), record.isOvercome());
    }

    public void addNewRecord(long uid, long qid, String original){
        boolean addResult = true;
        if(!wrongTitleRepository.findById(qid).isPresent())
            addResult = addNewWrongTitle(qid);
        if (!addResult) return;
        TitleRecord record = titleRecordRepository.findByUserIdAndQuestionId(uid,qid);
        if (record == null){
            record = new TitleRecord();
            record.setUserId(uid);
            record.setQuestionId(qid);
            record.setQuestionOriginal(original);
            userInfoService.addUserWrongTitleCount(uid);
        }else if(!record.getQuestionOriginal().contains(original)){
            record.setQuestionOriginal(record.getQuestionOriginal() + " " + original);
        }
        titleRecordRepository.save(record);
    }

    public boolean addNewWrongTitle(long qid){
        RawWrongTitle rawWrongTitle = restTemplateService.getWrongTitleFromDataBase(qid);
        if (rawWrongTitle == null)
            return false;
        RawWrongTitleBody titleBody = rawWrongTitle.getData();

        WrongTitle title = new WrongTitle();
        title.setQuestionId(qid);
        title.setQuestionContent(titleBody.getTopicContent());

        List<QuestionOption> questionOptionList = new ArrayList<>();
        for (String option : titleBody.getOptions())
            questionOptionList.add(new QuestionOption(qid, option));
        questionOptionRepository.saveAll(questionOptionList);

        List<QuestionAnswer> questionAnswerList = new ArrayList<>();
        for (String answer : titleBody.getAnswer())
            questionAnswerList.add(new QuestionAnswer(qid, answer));
        questionAnswerRepository.saveAll(questionAnswerList);

        List<TagTitleRecord> tagTitleRecordList = new ArrayList<>();
        for (String tag : titleBody.getTags()){
            if (tag.contains("年级"))
                title.setQuestionGrade(tag);
            else if (subjects.contains(tag))
                title.setQuestionSubject(tag);
            else if (questionType.contains(tag))
                title.setQuestionType(tag);
            else
                tagTitleRecordList.add(new TagTitleRecord(qid, tag));
        }
        if (title.getQuestionGrade() == null)
            title.setQuestionGrade("知识竞赛");
        tagTitleRecordRepository.saveAll(tagTitleRecordList);
        wrongTitleRepository.save(title);
        return true;
    }

    public void setFavorite(long uid, long qid, boolean isFavorite){
        TitleRecord record = titleRecordRepository.findByUserIdAndQuestionId(uid, qid);
        record.setFavorite(isFavorite);
        titleRecordRepository.save(record);
    }

    public void setOvercome(long uid, long qid, boolean isOvercome){
        TitleRecord record = titleRecordRepository.findByUserIdAndQuestionId(uid, qid);
        record.setOvercome(isOvercome);
        titleRecordRepository.save(record);
    }

    public void setDel(long uid, long qid, boolean isDel) {
        TitleRecord record = titleRecordRepository.findByUserIdAndQuestionId(uid, qid);
        UserInfo info = userInfoService.getUserInfoById(uid);
        if (record.isDel() && isDel)
            return;
        if (!record.isDel() && !isDel)
            return;
        int sum = isDel ? info.getWrongTitleCount() - 1 : info.getWrongTitleCount() + 1;
        info.setWrongTitleCount(sum);
        record.setDel(isDel);
        userInfoService.saveUserInfo(info);
        titleRecordRepository.save(record);
    }
}
